package work.sajor.wechatpush.controller;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import org.apache.commons.codec.digest.DigestUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import work.sajor.wechatpush.entiy.*;
import work.sajor.wechatpush.service.Pusher;
import work.sajor.wechatpush.service.SendMsg;
import work.sajor.wechatpush.util.WechatUtils;

import java.util.Arrays;
import java.util.List;

@RestController
public class WechatController {
    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 工具类
     */
    @Autowired
    Pusher pusherService;
    @Value("${target.test.openId}")
    private String testTarget;
    @Autowired
    private WechatUtils wechatUtils;
    @Autowired
    private SendMsg sendMsg;

    /**
     * 微信公众号接口配置验证
     *
     * @return
     */
    @RequestMapping(value = "/wechat", method = RequestMethod.GET)
    public String checkSignature(String signature, String timestamp,
                                 String nonce, String echostr) {
        logger.info("signature = {}", signature);
        logger.info("timestamp = {}", timestamp);
        logger.info("nonce = {}", nonce);
        logger.info("echostr = {}", echostr);
        // 第一步：自然排序
        String[] tmp = {WechatUtils.getToken(), timestamp, nonce};
        Arrays.sort(tmp);
        // 第二步：sha1 加密
        String sourceStr = StringUtils.join(tmp);
        String localSignature = DigestUtils.sha1Hex(sourceStr);
        // 第三步：验证签名
        if (signature.equals(localSignature)) {
            return echostr;
        }
        return null;
    }

    @RequestMapping("/getAccessToken")
    public void getAccessToken() {
        try {
            String accessToken = wechatUtils.getAccessToken();
            logger.info("access_token = {}", accessToken);
        } catch (WxErrorException e) {
            logger.error("获取access_token失败。", e);
        }
    }

    @RequestMapping("getUserInfo")
    public void getUserInfo() {
        try {
            WxMpUserList userList = wechatUtils.getUserList();

            if (userList == null || userList.getOpenids().isEmpty()) {
                logger.warn("关注者openId列表为空");
                return;
            }
            List<String> openIds = userList.getOpenids();
            logger.info("关注者openId列表 = {}", openIds.toString());

            String openId = openIds.get(0);
            logger.info("开始获取 {} 的基本信息", openId);
            WxMpUser userInfo = wechatUtils.getUserInfo(openId);
            if (userInfo == null) {
                logger.warn("获取 {} 的基本信息为空", openId);
                return;
            }
            String city = userInfo.getCity();
            String nickname = userInfo.getNickname();
            logger.info("{} 的昵称为：{}, 城市为：{}", openId, nickname, city);
        } catch (WxErrorException e) {
            logger.error("获取用户消息失败", e);
        }
    }

    /**
     * 接收用户消息
     *
     * @param receiveMsgBody 消息
     * @return
     */
    @RequestMapping(value = "/wechat", method = RequestMethod.POST, produces = {"application/xml; charset=UTF-8"})
    @ResponseBody
    public Object getUserMessage(@RequestBody ReceiveMsgBody receiveMsgBody) {
        logger.info("接收到的消息：{}", JSONObject.toJSONString( receiveMsgBody));
        MsgType msgType = MsgType.getMsgType(receiveMsgBody.getMsgType());
        if (ObjectUtils.isEmpty(msgType)) {
            return null;
        }
        msg msg = new msg();
        switch (msgType) {
            case text:
                logger.info("接收到的消息类型为{}", MsgType.text.getMsgTypeDesc());
                ResponseMsgBody textMsg = new ResponseMsgBody();
                textMsg.setToUserName(receiveMsgBody.getFromUserName());
                textMsg.setFromUserName(receiveMsgBody.getToUserName());
                textMsg.setCreateTime(System.currentTimeMillis());
                textMsg.setMsgType(MsgType.text.getMsgType());
                textMsg.setContent(receiveMsgBody.getContent());
                if (receiveMsgBody.getFromUserName().equals("o7w1R6X3TDVBHYnZELPH3XjFnNxo")) {
                    sendMsg.sendMsg("o7w1R6ZfgnDTYZHpQltMWslWgmQQ", receiveMsgBody.getContent());
                    sendMsg.sendMsg(testTarget, receiveMsgBody.getContent());
                } else if (receiveMsgBody.getFromUserName().equals("o7w1R6ZfgnDTYZHpQltMWslWgmQQ")) {
                    sendMsg.sendMsg("o7w1R6X3TDVBHYnZELPH3XjFnNxo", receiveMsgBody.getContent());
                    pusherService.pushMsg(testTarget, receiveMsgBody.getFromUserName(), receiveMsgBody.getContent());
                } else if (receiveMsgBody.getFromUserName().equals(testTarget)) {
                    sendMsg.sendMsg("o7w1R6X3TDVBHYnZELPH3XjFnNxo", receiveMsgBody.getContent());
                } else {
                    pusherService.pushMsg(testTarget, receiveMsgBody.getFromUserName(), receiveMsgBody.getContent());
                }
                return "";
            case image:
                logger.info("接收到的消息类型为{}", MsgType.image.getMsgTypeDesc());
                if (receiveMsgBody.getFromUserName().equals("o7w1R6X3TDVBHYnZELPH3XjFnNxo")) {
                    msg.setTouser("o7w1R6ZfgnDTYZHpQltMWslWgmQQ");
                } else if (receiveMsgBody.getFromUserName().equals("o7w1R6ZfgnDTYZHpQltMWslWgmQQ")) {
                    msg.setTouser("o7w1R6X3TDVBHYnZELPH3XjFnNxo");
                } else if (receiveMsgBody.getFromUserName().equals(testTarget)) {
                    msg.setTouser("o7w1R6X3TDVBHYnZELPH3XjFnNxo");
                } else {
                    pusherService.pushMsg(testTarget, receiveMsgBody.getFromUserName(), receiveMsgBody.getContent());
                }
                msg.setImage(new Image(receiveMsgBody.getMediaId()));
                msg.setMsgtype("image");
                sendMsg.sendMessage(msg);
                return "";

            case voice:
                logger.info("接收到的消息类型为{}", MsgType.voice.getMsgTypeDesc());
                if (receiveMsgBody.getFromUserName().equals("o7w1R6X3TDVBHYnZELPH3XjFnNxo")) {
                    msg.setTouser("o7w1R6ZfgnDTYZHpQltMWslWgmQQ");
                } else if (receiveMsgBody.getFromUserName().equals("o7w1R6ZfgnDTYZHpQltMWslWgmQQ")) {
                    msg.setTouser("o7w1R6X3TDVBHYnZELPH3XjFnNxo");
                } else if (receiveMsgBody.getFromUserName().equals(testTarget)) {
                    msg.setTouser("o7w1R6X3TDVBHYnZELPH3XjFnNxo");
                } else {
                    pusherService.pushMsg(testTarget, receiveMsgBody.getFromUserName(), receiveMsgBody.getContent());
                }
                msg.setVoice(new Voice(receiveMsgBody.getMediaId()));
                msg.setMsgtype("voice");
                sendMsg.sendMessage(msg);
                return "";
            case video:
                logger.info("接收到的消息类型为{}", MsgType.voice.getMsgTypeDesc());
                if (receiveMsgBody.getFromUserName().equals("o7w1R6X3TDVBHYnZELPH3XjFnNxo")) {
                    msg.setTouser("o7w1R6ZfgnDTYZHpQltMWslWgmQQ");
                } else if (receiveMsgBody.getFromUserName().equals("o7w1R6ZfgnDTYZHpQltMWslWgmQQ")) {
                    msg.setTouser("o7w1R6X3TDVBHYnZELPH3XjFnNxo");
                } else if (receiveMsgBody.getFromUserName().equals(testTarget)) {
                    msg.setTouser("o7w1R6X3TDVBHYnZELPH3XjFnNxo");
                } else {
                    pusherService.pushMsg(testTarget, receiveMsgBody.getFromUserName(), receiveMsgBody.getContent());
                }
                msg.setVideo(new Video(receiveMsgBody.getMediaId(),receiveMsgBody.getMediaId(),"TITLE","DESCRIPTION"));
                msg.setMsgtype("video");
                sendMsg.sendMessage(msg);
                return "";
            default:
                // 其他类型
                break;
        }
        return null;
    }

    @GetMapping("sengMsg/test")
    public void sendMsgtoMe(@RequestParam String msg) {
        SendMsg sendMsg = new SendMsg();
        sendMsg.sendMsg("o7w1R6a0_l6NQwe9DQtsdoFgJ2SI", msg);
    }

    @GetMapping("sengMsg")
    public void sendMsg(@RequestParam String msg) {
        SendMsg sendMsg = new SendMsg();
        sendMsg.sendMsg("o7w1R6ZfgnDTYZHpQltMWslWgmQQ", msg);
    }

    @GetMapping("sendMsgtoUser")
    public void sendMsgtoUser(@RequestParam String msg, @RequestParam String OpenId) {
        SendMsg sendMsg = new SendMsg();
        sendMsg.sendMsg(OpenId, msg);
    }

}
